package logics

import (
	"encoding/json"
	_const "git.900sui.cn/kc/apiPay/lang/const"
	"git.900sui.cn/kc/base/common/functions"
	"git.900sui.cn/kc/base/utils"
	pay2 "git.900sui.cn/kc/rpcinterface/client/pay"
	"git.900sui.cn/kc/rpcinterface/interface/pay"
	"log"
)

//支付宝支付
type AlipayLogic struct{}

func (this *AlipayLogic) Do(t functions.Controller, orderSnField, cidFiled string) {
	order_sn := t.Ctx.GetString(orderSnField)
	cid := t.Ctx.GetString(cidFiled)
	utils.Logerr.Printf("order_sn : %s", order_sn)
	utils.Logerr.Printf("cid : %s", cid)
	auth_code := t.Input.Post("auth_code").String()
	app_id := t.Input.Post("app_id").String()
	scope := t.Input.Post("scope")
	if len(auth_code) == 0 || len(app_id) == 0 || len(scope) == 0 {
		t.Output.Error(_const.ParamError)
		return
	}
	utils.Logerr.Printf("authcode: %s, app_id:%s, scope : %s", auth_code, app_id, scope)
	client := new(pay2.XindaluPay).Init()
	args := &pay.ArgsGetAliUserInfo{
		Code:          auth_code,
		GrantType:     "authorization_code",
		RefreshTtoken: "",
		Cid:           cid,
	}
	reply := &pay.ReplyGetAliUserInfo{}
	err := client.GetAliUserInfo(t.Ctx.Request.Context(), args, reply)
	if err != nil {
		t.Output.Error(_const.AliGetUserError, err.Error())
		return
	}
	userid := reply.UserId

	orderArgs := &pay.ArgsunionidOrder{
		OrderNO: order_sn,
		Openid:  userid,
		PayWay:  pay.PayWayAli,
		Ip:      functions.ClientIP(t.Ctx.Request),
		Cid:     cid,
	}
	orderReply := &pay.ReplyUniondOrder{}
	err = client.UnionidOrder(t.Ctx.Request.Context(), orderArgs, orderReply)
	if err != nil {
		t.Output.Error(_const.RpcServerIsError, err.Error())
		return
	}
	jsonByte, _ := json.Marshal(orderReply.Data)
	log.Printf("json: %s", string(jsonByte))
	t.Output.Success(orderReply.Data)
}
